import { Form, Button, message } from 'antd'
import { ImportantEditModal } from '@/desktop/components'
import { WordsInput } from '@/desktop/components/words'
import services from '@/services'
import type { Words } from '@/services/resources/words-library'
import WordsGroupInput from './WordsGroup'
import './index.module.less'

export default function EditWords(props: {
  words: true | Words | null
  isGlobal: boolean
  onFinish: () => void
}) {
  const { isGlobal, words, onFinish } = props
  const title = `${words === true ? '创建' : '编辑'}${isGlobal ? '全员' : ''}话术`

  return <ImportantEditModal
    open={words !== null}
    title={title}
    footer={null}
    width="750px"
    onCancel={onFinish}
  >
    {words !== null ? <Content isGlobal={isGlobal} words={words} onFinish={onFinish} /> : null}
  </ImportantEditModal>
}

function Content(props: { words: true | Words; isGlobal: boolean; onFinish: () => void }) {
  const { words, isGlobal, onFinish } = props
  const initialValues = useMemo(() => {
    if (words === true) return { groupId: null, items: [] }
    return { groupId: words.groupId, items: words.items }
  }, [words])

  const [submitting, setSubmitting] = useState(false)
  const onSubmit = useCallback(
    async (values: typeof initialValues) => {
      setSubmitting(true)
      const res = await services.resources.wordsLibrary.addOrUpdate({
        id: words === true ? undefined : words.id,
        isGlobal,
        groupId: values.groupId,
        items: values.items,
      })
      setSubmitting(false)

      if (res.success) onFinish()
      else void message.warning(`保存失败：${res.error}`)
    },
    [words, isGlobal, onFinish],
  )

  return <Form
    styleName="form"
    initialValues={initialValues}
    labelCol={{ span: 3 }}
    onFinish={onSubmit}
  >
    <main>
      <Form.Item label="话术分组" name="groupId">
        <WordsGroupInput isGlobal={isGlobal} />
      </Form.Item>

      <Form.Item label="添加" name="items" rules={[{ required: true, message: '请添加话术内容' }]}>
        <WordsInput />
      </Form.Item>
    </main>
    <footer>
      <Button onClick={onFinish}>取消</Button>
      <Button type="primary" htmlType="submit" loading={submitting}>
        保存
      </Button>
    </footer>
  </Form>
}
